package com.jluzh10.learning.utils.qiniu;

import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author yzg
 * @create 2019/5/24
 *
 * 七牛云上传下载工具类
 */
@Component
public class QiniuUtil {
    private static QiniuConfig qiniuConfig;
    //华南区
    private static UploadManager uploadManager=new UploadManager(new Configuration(Zone.zone2()));


    public static String uploadFile(InputStream inputStream, String key) throws IOException {
        Auth auth = Auth.create(qiniuConfig.getAccesskey(), qiniuConfig.getSecretkey());
        String token = auth.uploadToken(qiniuConfig.getBucket());
        byte[] byteData = IOUtils.toByteArray(inputStream);
        Response response = uploadManager.put(byteData, key, token, null, null,
                false);
        inputStream.close();
        DefaultPutRet ret = response.jsonToObject(DefaultPutRet.class);
        return ret.key;
    }

    /**
     * 获取轮播图图片链接
     * @param key
     * @return
     */
    public static String getUrlByCarousel(String key){
        if (key==null||"".equals(key)){
            return null;
        }
        return "http://"+qiniuConfig.getCdns()+"/"+key+"?"+qiniuConfig.getPictureCarousel();
    }

    /**
     * 获取课程封面链接
     * @param key
     * @return
     */
    public static String getUrlByCourse(String key){
        if (key==null||"".equals(key)){
            return null;
        }
        return "http://"+qiniuConfig.getCdns()+"/"+key+"?"+qiniuConfig.getPictureCourse();
    }

    /**
     * 获取头像图片链接
     * @param key
     * @return
     */
    public static String getUrlByHead(String key){
        if (key==null||"".equals(key)){
            return null;
        }
        return "http://"+qiniuConfig.getCdns()+"/"+key+"?"+qiniuConfig.getPictureHead();
    }

    /**
     * 获取原格式链接
     * @param key
     * @return
     */
    public static String getUrl(String key){
        if (key==null||"".equals(key)){
            return null;
        }
        return "http://"+qiniuConfig.getCdns()+"/"+key;
    }


    @Autowired
    public void setQiniuConfig(QiniuConfig qiniuConfig) {
        QiniuUtil.qiniuConfig = qiniuConfig;
    }
}

